package com.tutu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tutu.commons.checks.UserCheckParam;
import com.tutu.commons.constants.ConstsntsParam;
import com.tutu.commons.utils.MD5Util;
import com.tutu.commons.utils.R;
import com.tutu.user.mapper.UserMapper;
import com.tutu.commons.pojo.User;
import com.tutu.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @Program: b2c-cloud-store
 * @Description:
 * @Author: JK.TuTu
 * @Version: 1.0
 * @Create: 2022-12-13 19:34
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    /**
     * 通过用户名检查用户是否存在
     *
     * @param userCheckParam 前端传递参数 校验
     * @return 返回结果实体对象
     */
    @Override
    public boolean checkUserExist(UserCheckParam userCheckParam) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userCheckParam.getUserName());
        Long count = userMapper.selectCount(queryWrapper);
        return count>0;
    }


    /**
     * 用户注册
     * @param user 接受前端注册参数
     */
    @Override
    public R register(User user) {
        UserCheckParam userCheckParam = new UserCheckParam();
        userCheckParam.setUserName(user.getUserName());
        //校验注册用户是否存在
        if(checkUserExist(userCheckParam)){
            return R.fail("账号已存在,不可注册!");
        }
        try{
            //使用MD5工具类 对用户密码进行加盐加密处理
            String newPwd = MD5Util.encode(user.getPassword() + ConstsntsParam.USER_SALT);
            user.setPassword(newPwd);
            userMapper.insert(user);
        }catch (Exception e) {
            return R.fail("注册错误!");
        }
        return R.ok("注册成功!");
    }


    /**
     * 用户登录
     * @param user 登录时的参数
     * @return 返回结果实体对象
     */
    @Override
    public R login(User user) {
        //检查用户名是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,user.getUserName());
        User userDB = userMapper.selectOne(queryWrapper);
        if(ObjectUtils.isEmpty(userDB)){
            return R.fail("该用户名不存在!");
        }
        //对密码明文进行加密
        String newPwd = MD5Util.encode(user.getPassword() + ConstsntsParam.USER_SALT);
        if(!userDB.getPassword().equals(newPwd)){
            return R.fail("密码错误!");
        }
        userDB.setPassword(null);
        userDB.setUserPhoneNumber(null);
        return R.ok("登录成功!",userDB);
    }
}
